package com.zhongfl.crm.lixiao.batch.service;

import com.heptagram.lixiao.api.LiXiaoService;
import com.heptagram.lixiao.bean.LiXiaoConsts;
import com.heptagram.lixiao.bean.enums.OpportunityStage;
import com.heptagram.lixiao.bean.response.opportunity.LXOpportunityListResponse;
import com.heptagram.lixiao.bean.response.opportunity.LXOpportunityResponse;
import com.heptagram.lixiao.common.exception.LiXiaoErrorException;
import com.zhongfl.crm.enums.boss.MessageSendType;
import com.zhongfl.crm.enums.boss.OrderStatus;
import com.zhongfl.crm.lixiao.bean.resolve.OrderModelResolver;
import com.zhongfl.crm.lixiao.common.ListUtils;
import com.zhongfl.crm.lixiao.common.LxOrderListUtils;
import com.zhongfl.crm.lixiao.config.MailConfigInfo;
import com.zhongfl.crm.lixiao.mapper.LXCustomFieldsMapper;
import com.zhongfl.crm.lixiao.mapper.LXOrderMapper;
import com.zhongfl.crm.service.boss.CustomerOrderService;
import com.zhongfl.crm.service.boss.LXOrderService;
import com.zhongfl.crm.service.boss.MessageSendTaskService;
import com.zhongfl.crm.mail.MailService;
import com.zhongfl.crm.mail.bean.MailMessage;
import com.zhongfl.crm.mail.bean.MailMessageBuilder;
import com.zhongfl.crm.mail.enums.MailTypeEnum;
import com.zhongfl.crm.model.boss.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.joda.time.Hours;
import org.joda.time.LocalDateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.heptagram.channel.api.model.Channel;
import tech.heptagram.channel.api.service.ChannelService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 励销订单同步到BOSS 服务
 * 1. 新订单同步
 * 1.1 创建boss客户订单
 * 1.2 根据boss客户订单创建多个交付订单
 * 1.3 回调CRM合同接口创建多个交付订单
 * <p>
 * 2. 更新订单信息同步
 * 2.1 更新客户订单
 * 2.2 更新交付订单(不更新，励销无人维护交付订单)
 *
 * @author wang.yuchuan
 * @date 2018/6/25
 */
@Service
@Slf4j
public class OrderSyncFromLX2BossService {

    /**
     * 只同步1小时之内创建的订单, 服务会5分钟跑一次。
     */
    public static final int NEW_ORDER_HOURS_SYNC = 1;

    /**
     * 只更新1小时之内的订单
     */
    public static final int UPDATE_ORDER_HOURS_SYNC = 1;

    @Resource
    private LxOrderListUtils lxOrderListUtils;
    @Resource
    private LiXiaoService liXiaoService;
    @Resource
    private OrderModelResolver orderModelResolver;
    @Resource
    private LXOrderService lxOrderService;
    @Resource
    private LXOrderMapper lxOrderMapper;
    @Resource
    private MailConfigInfo mailConfigInfo;
    @Resource
    private MailService mailService;
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;
    @Resource
    private MessageSendTaskService messageSendTaskService;
    @Resource
    private CustomerOrderService customerOrderService;
    @Resource
    private LXCustomFieldsMapper lxCustomFieldsMapper;
    @Resource
    private ChannelService channelService;

    public void newOrderSync(Integer syncHours) throws LiXiaoErrorException, InterruptedException {
        int pageIndex = 1;
        // 励销线索查询结果
        LXOpportunityListResponse opportunitiesResponse;
        do {
            opportunitiesResponse = lxOrderListUtils.findOpportunities(pageIndex, LxOrderListUtils.SORT_MODE_CREATED);
            if (Objects.isNull(opportunitiesResponse)) {
                log.info("没有查询到新的线索信息");
                return;
            }

            List<LXOpportunityListResponse.Opportunity> opportunities = opportunitiesResponse.getData().getOpportunities();

            for (LXOpportunityListResponse.Opportunity lxOrder : opportunities) {
                try {

                    if (Objects.isNull(syncHours)) {
                        syncHours = NEW_ORDER_HOURS_SYNC;
                    }
                    if (!needDeal(lxOrder.getCreatedAt(), syncHours)) {
                        log.info("客户订单:{} 创建时间已超过 {} 小时, 没有需要同步的数据.", lxOrder.getTitle(), NEW_ORDER_HOURS_SYNC);
                        return;
                    }

                    Thread.sleep(2000);
                    LXOpportunityResponse opportunity = liXiaoService.getOpportunityService().findOpportunityByOrderId(lxOrder.getId());
                    syncSingleLxOrder2Boss(opportunity.getData());

                } catch (Exception ex) {
                    log.error("同步订单错误: {}", ex.getMessage(), ex);
                    sendNotifyMail(lxOrder, ex.getMessage());
                }
            }

            pageIndex = pageIndex + 1;
            // 万恶的励销, 1次/秒的调用限制?
            Thread.sleep(2000);
        } while (opportunitiesResponse.getData().hasNextPage());
    }

    /**
     * 同步CRM新录入的订单到BOSS系统
     */
    public void newOrderSync() throws LiXiaoErrorException, InterruptedException {
        newOrderSync(NEW_ORDER_HOURS_SYNC);
    }

    private boolean needDeal(String startTime, int hours) {
        if (StringUtils.isNotEmpty(startTime)) {
            LocalDateTime createdAt = LocalDateTime.parse(startTime, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"));
            int between = Hours.hoursBetween(createdAt, LocalDateTime.now()).getHours();
            log.info("startTime:{} hours:{}, between:{}", startTime, hours, between);

            if (between > hours) {
                return false;
            }
        }
        return true;
    }

    /**
     * 同步单条励销订单到boss
     * <p>
     * 以前的逻辑：
     * 1.查询中间表，如果已经同步过次订单，则跳过
     * 2.先保存订单到boss,再保存同步记录到中间表
     * 3.发送订单采集工单创建消息，创建采集工单
     * <p>
     * 现在的逻辑：
     * 1.查询中间表，如果已经同步过次订单，则跳过
     * 2.同步订单
     * 2.1 先保存客户订单表
     * 2.2 根据lxOrder和客户订单号，生成多条交付订单（其中包括交付部门信息）
     * 2.3 将交付订单号更新到客户订单
     * 2.4 创建中间表订单
     * 2.5 为每个交付订单创建资料采集工单
     * 2.6 最新碰到的问题是：当我们同步交付订单到励销以后，励销会在创建第一条合同的时候，自动将商机转为赢单。
     * 所以在这里我们再次更新励销的商机：订单状态为已创建。
     */
    @Transactional(rollbackFor = Exception.class)
    public void syncSingleLxOrder2Boss(LXOpportunityResponse.DataResult lxOrder) throws ParseException {
        log.info("客户订单: {} 开始同步", lxOrder.getTitle());

        // 如果订单已经在同步表存在, 则跳过此订单
        LxOrder localLxOrder = lxOrderMapper.selectByLxIdAndOrderType(lxOrder.getId(), LiXiaoConsts.QueryEntity.opportunity);
        if (Objects.nonNull(localLxOrder)) {
            log.info("订单:{} 已存在, 跳过", lxOrder.getTitle());
            return;
        }

        log.info("订单:{} 不存在, 创建此订单", lxOrder.getTitle());

        // 1. 创建BOSS客户订单
        log.info("创建客户订单开始：", lxOrder.getTitle());
        CustomerOrder customerOrder = orderModelResolver.resolve2CustomerOrder(lxOrder);
        customerOrder.setCustomerOrderStatus(OrderStatus.STATUS_CREATED.name());
        String customerOrderNo = customerOrderService.saveCustomerOrder(customerOrder);
        if (StringUtils.isEmpty(customerOrderNo)) {
            log.info("创建客户订单失败！！！", lxOrder.getTitle());
            return;
        }
        log.info("创建客户订单完成！", lxOrder.getTitle());

        // 2. 保存客户订单到lx_order
        log.info("保存订单同步记录开始：", lxOrder.getTitle());
        localLxOrder = orderModelResolver.resolveLXOrder(lxOrder);
        localLxOrder.setOrderNo(customerOrderNo);
        localLxOrder.setOrderType(LiXiaoConsts.QueryEntity.opportunity);
        lxOrderMapper.insertSelective(localLxOrder);
        log.info("保存订单同步记录完成！", lxOrder.getTitle());

        log.info("客户订单:{} 已保存到本地, 同步成功", lxOrder.getTitle());

        // 3. 创建交付订单
        log.info("创建交付订单开始：", lxOrder.getTitle());
        this.saveDeliveryOrders(lxOrder, customerOrderNo);
        log.info("创建交付订单完成！", lxOrder.getTitle());


//        log.info("开始同步客户订单:{} 的交付订单到励销", lxOrder.getTitle());
//        this.createDeliveryOrderInLiXiaoByBossCustomerOrder(customerOrderNo);
//        log.info("同步交付订单到励销完成");
//
//        log.info("开始将励销的商机'赢单'状态还原为'已创建'");
//        revertLxDeliveryOrderStatus(lxOrder);
//        log.info("还原商机状态成功");
    }

    private void saveDeliveryOrders(LXOpportunityResponse.DataResult lxOrder, String customerOrderNo) {
        List<String> deliveryAmibaList = lxOrder.getTextAsset6517e5();

        for (String lxDeliveryAmibaId : deliveryAmibaList) {
            LXCustomFields lxCustomField = lxCustomFieldsMapper.selectByOptionValue(lxDeliveryAmibaId);
            if (Objects.isNull(lxCustomField)) {
                sendNotifyMail(lxOrder, "boss未查询到励销选项为：" + lxDeliveryAmibaId + "的交付巴信息！交付订单未创建");
                continue;
            }

            try {
                String deliveryOrderNo = this.saveSingleDeliveryOrder(lxOrder, lxCustomField.getOptionDesc(), customerOrderNo);

                this.createInformationMessage(deliveryOrderNo, lxCustomField.getOptionDesc(), lxOrder.getUser().getId(), lxOrder.getId());
            } catch (Exception ex) {
                log.error("同步订单错误: {}", ex.getMessage(), ex);
                CompletableFuture.runAsync(() ->
                    sendNotifyMail(lxOrder, ex.getMessage()), taskExecutor)
                    .whenCompleteAsync((v, e) -> log.info("发送邮件完成"));
            }
        }
    }

    private String saveSingleDeliveryOrder(LXOpportunityResponse.DataResult lxOrder, String deliveryAmibaId, String customerOrderNo) {
        Order order = orderModelResolver.resolve(lxOrder);
        order.setCustomerOrderNo(customerOrderNo);
        order.setDeliverManagerAmibaId(Integer.valueOf(deliveryAmibaId));
        return lxOrderService.save(order);
    }

    private void createInformationMessage(String deliveryOrderNo, String deliveryAmibaId, Long lxUserId, Long lxCustomerOrderId) {
        log.info("开始创建交付订单：{} 的采集工单", deliveryOrderNo);

        //自动创建采集工单消息通知
        OrderCreatedMessage orderCreatedMessage = new OrderCreatedMessage();
        orderCreatedMessage.setOrderNo(deliveryOrderNo);
        orderCreatedMessage.setDeliveryAmibaId(deliveryAmibaId);
        orderCreatedMessage.setLxUserId(lxUserId);
        orderCreatedMessage.setLxId(lxCustomerOrderId);

        //消息通知任务日志
        messageSendTaskService.save(MessageSendType.ORDER_CREATED_MSG,
            orderCreatedMessage.getOrderNo(),
            UUID.randomUUID().toString(),
            TopicConsts.CREATED_ORDER_INFORMATION_NOTIFY_TOPIC,
            orderCreatedMessage);
    }

    /**
     * 同步励销更新的客户订单信息到Boss系统
     */
    public void changeOrderSync() throws LiXiaoErrorException, InterruptedException {
        int pageIndex = 1;
        // 励销线索查询结果
        LXOpportunityListResponse opportunitiesResponse;
        do {
            opportunitiesResponse = lxOrderListUtils.findOpportunities(pageIndex, LxOrderListUtils.SORT_MODE_UPDATED);
            if (Objects.isNull(opportunitiesResponse)) {
                log.info("没有查询到更新的机会信息");
                return;
            }
            List<LXOpportunityListResponse.Opportunity> opportunities = opportunitiesResponse.getData().getOpportunities();
            for (LXOpportunityListResponse.Opportunity lxOrder : opportunities) {
                try {
                    log.info("lxOrder:{}", lxOrder);
                    if (!needDeal(lxOrder.getUpdatedAt(), UPDATE_ORDER_HOURS_SYNC)) {
                        log.info("客户订单:{} 最后更新时间已超过 {} 小时, 没有需要同步的数据.", lxOrder.getTitle(), UPDATE_ORDER_HOURS_SYNC);
                        return;
                    }
                    Thread.sleep(2000);
                    LXOpportunityResponse opportunity = liXiaoService.getOpportunityService().findOpportunityByOrderId(lxOrder.getId());
                    //log.info("从励销获取的交付订单信息为{}", opportunity.toJson());
                    updateSingleCustomerOrder2Boss(opportunity.getData());
                } catch (Exception ex) {
                    log.error("从励销更新订单错误:" + ex);
                    sendNotifyMail(lxOrder, ex.getMessage());
                }
            }

            pageIndex = pageIndex + 1;
            // 万恶的励销, 1次/秒的调用限制?
            Thread.sleep(2000);
        } while (opportunitiesResponse.getData().hasNextPage());
    }

    /**
     * 更新方案：
     * 1.如果中间表不存在，跳过
     * 2.中间表订单号为空，跳过
     * 3.客户订单不存在，跳过
     * 4.更新中间表
     * 5.更新客户订单
     * 6.更新交付订单
     * 这里存在两个问题：（已解决）
     * 一：商务去掉某个交付巴，对应交付订单应该删除。
     * 二：商务取消客户订单，所有的交付订单应该取消。
     */
    private void updateSingleCustomerOrder2Boss(LXOpportunityResponse.DataResult lxOrder) throws ParseException {
        log.info("客户订单: {} 开始更新", lxOrder.getTitle());

        LxOrder localLxOrder = lxOrderMapper.selectByLxIdAndOrderType(lxOrder.getId(), LiXiaoConsts.QueryEntity.opportunity);
        if (Objects.isNull(localLxOrder)) {
            log.info("订单:{} 还没有同步, 跳过", lxOrder.getTitle());
            return;
        }

        // 如果没有找到boss对应订单, 跳过。
        if (StringUtils.isEmpty(localLxOrder.getOrderNo())) {
            log.info("订单:{} 没有找到对应的boss订单, 跳过", lxOrder.getTitle());
            return;
        }

        CustomerOrder customerOrder = customerOrderService.findCustomerOrderByCustomerOrderNo(localLxOrder.getOrderNo());
        if (Objects.isNull(customerOrder)) {
            log.info("订单:{} 没有找到对应的boss订单, 跳过", lxOrder.getTitle());
            return;
        }

        // 如果某些信息发生变更
        if (customerOrderInfoChanged(lxOrder, customerOrder)) {
            // 更新中间表
            LxOrder resolveLXOrder = orderModelResolver.resolveLXOrder(lxOrder);
            BeanUtils.copyProperties(resolveLXOrder, localLxOrder);
            lxOrderMapper.updateByPrimaryKeySelective(localLxOrder);

            // 更新boss客户订单基本信息
            CustomerOrder updateCustomerOrder = orderModelResolver.resolve2CustomerOrder(lxOrder);
            updateCustomerOrder.setCustomerOrderNo(customerOrder.getCustomerOrderNo());
            if(!shouldSyncAmount(customerOrder)) {
                updateCustomerOrder.setLoanAmount(null);
                updateCustomerOrder.setLoanDuration(null);
            }
            customerOrderService.updateByCustomerOrderNo(updateCustomerOrder);

            // todo 更新boss交付订单基本信息 存在将某一交付部门信息同步到其他交付订单的问题
            updateDeliveryOrders(customerOrder.getCustomerOrderNo());

            log.info("更新boss订单完成: 客户:{} 金额:{} 渠道:{}", customerOrder.getCustomerName(), customerOrder.getLoanAmount(), customerOrder.getChannelName());
        } else {
            log.info("订单信息未发生改变，跳过更新！");
        }

        Date createDate = DateUtils.parseDate(lxOrder.getCreatedAt(), "yyyy-MM-dd HH:mm");
        Date systemDate = DateUtils.parseDate("2018-09-17", "yyyy-MM-dd");

        if (createDate.before(systemDate)) {
            log.info("订单创建时间早于2018-09-17，不进行交付部门的调整和订单的取消！");
            return;
        }

        // 考虑如果交付部门发生变化?
        this.adjustDeliveryOrdersByCustomerOrder(lxOrder, customerOrder);

        // 考虑如果客户订单被商务取消?
        log.info("开始对励销客户订单取消状态进行检查");
        if (Objects.equals(lxOrder.getStage(), OpportunityStage.STATUS_FAILED.getId().toString())) {
            log.info("励销客户订单已取消！");
            if (customerOrder.getKhOrderStatus().equals(OrderStatus.STATUS_CANCEL)) {
                log.info("客户订单BOSS系统已取消，无需进行订单取消");
            } else {
                log.info("开始对BOSS系统客户订单及交付订单进行取消");
                customerOrderService.cancelCustomerOrder(customerOrder.getCustomerOrderNo(), customerOrder.getBusinessManagerStaffName());
                log.info("对BOSS系统客户订单及交付订单进行取消，完成");
            }
        }
        log.info("对励销客户订单取消状态检查，完成");

        log.info("客户订单: {} 更新完成", lxOrder.getTitle());
    }

    /**
     * 判断励销客户订单与BOSS客户订单信息是否一致
     *
     * @param lxCustomerOrder 励销客户订单
     * @param customerOrder   BOSS客户订单
     * @return true 如果励销订单发生变更, false 如果两者一致
     * @throws ParseException
     */
    private boolean customerOrderInfoChanged(LXOpportunityResponse.DataResult lxCustomerOrder, CustomerOrder customerOrder) throws ParseException {
        if (!customerOrder.getCustomerName().equals(lxCustomerOrder.getTitle())) {
            return true;
        }

        if (!customerOrder.getChannelName().equals(lxCustomerOrder.getCustomer().getName())) {
            return true;
        }

        BigDecimal lxLoanAmount = new BigDecimal(lxCustomerOrder.getExpectAmount());
        if (customerOrder.getLoanAmount().compareTo(lxLoanAmount) != 0) {
            return true;
        }

        if (customerOrder.getLoanDuration() != lxCustomerOrder.getNumericAssetF59409().intValue()) {
            return true;
        }

        if (customerOrder.getTotalFeeRate().compareTo(lxCustomerOrder.getNumericAsset7de9b6()) != 0) {
            return true;
        }

        if (customerOrder.getChannelFeeRate().compareTo(lxCustomerOrder.getNumericAsset86eeee()) != 0) {
            return true;
        }

        if (Objects.nonNull(lxCustomerOrder.getGetTime())) {
            Date lxGetTime = DateUtils.parseDate(lxCustomerOrder.getGetTime(), "yyyy-MM-dd");
            if (!DateUtils.isSameDay(lxGetTime, customerOrder.getInterviewDate())) {
                return true;
            }
        }

        Channel channel = channelService.findById(customerOrder.getChannelId());
        if (channel.getLxCustomerId().longValue() != lxCustomerOrder.getCustomer().getId()) {
            return true;
        }

        return false;
    }

    /**
     * 是否应该同步金额信息
     *
     * @param customerOrder
     * @return
     */
    private boolean shouldSyncAmount(CustomerOrder customerOrder) {
        switch (customerOrder.getKhOrderStatus()) {
            case STATUS_CREATED:
                return true;
            case STATUS_COLLECT:
                return true;
            case STATUS_DECLARE:
                return true;
            case STATUS_APPROVAL:
                return true;
            case STATUS_PIDAI:
                return false;
            case STATUS_STORAGE:
                return false;
            case STATUS_APPLICAT:
                return false;
            case STATUS_ACCOUNT:
                return false;
            case STATUS_COMPLETED:
                return false;
            case STATUS_CANCEL:
                return false;
            case STATUS_CUSTOM:
                return true;
            case STATUS_CUSTOM_DELIVER:
                return true;
            default:
                return true;
        }
    }

    private void updateDeliveryOrders(String customerOrderNo) {
        CustomerOrder customerOrder = customerOrderService.findCustomerOrderByCustomerOrderNo(customerOrderNo);
        List<Order> deliveryOrderList = lxOrderService.findListByCustomerOrderNo(customerOrderNo);

        List<Order> collect = deliveryOrderList.stream()
            .filter(order -> !Objects.equals(order.getStatus(), OrderStatus.STATUS_CANCEL))
            .collect(Collectors.toList());

        collect.forEach(order -> {
            Order updateInfo = new Order();
            updateInfo.setOrderNo(order.getOrderNo());
            updateInfo.setCustomerOrderNo(customerOrderNo);
            updateInfo.setName(customerOrder.getCustomerName());
            if(shouldSyncAmount(customerOrder)) {
                updateInfo.setLoanAmount(customerOrder.getLoanAmount().divide(new BigDecimal(10000)));
                updateInfo.setLoanDuration(customerOrder.getLoanDuration());
            }
            updateInfo.setTotalFeeRate(customerOrder.getTotalFeeRate());
            updateInfo.setChannelRate(customerOrder.getChannelFeeRate());
            updateInfo.setChannelId(customerOrder.getChannelId());
            updateInfo.setChannelName(customerOrder.getChannelName());
            updateInfo.setCreatedBy(customerOrder.getBusinessManagerStaffName());
            updateInfo.setCurrentStaffCode(customerOrder.getBusinessManagerStaffCode());
            updateInfo.setCurrentStaffName(customerOrder.getBusinessAssistantStaffName());

            lxOrderService.update(updateInfo);
        });
    }

    /**
     * 根据客户订单上选择的交付巴调整交付订单
     * 1.取励销客户订单和本地交付订单交付巴ID进行比较，取出差集部分
     * 2.对差集里的交付巴ID进行新增交付订单和取消交付订单
     */
    private void adjustDeliveryOrdersByCustomerOrder(LXOpportunityResponse.DataResult lxOrder, CustomerOrder customerOrder) {
        // 输单不是订单的正常状态,不应根据输单的客户订单上的交付部门来进行交付部门的调整
        if (lxOrder.getStage().equals(OpportunityStage.STATUS_FAILED.getId().toString())) {
            return;
        }

        log.info("开始进行受理交付部门更新调整");

        List<String> deliveryAmibaList = lxOrder.getTextAsset6517e5();
        List<String> externalList = new ArrayList<>();
        for (String lxDeliveryAmibaId : deliveryAmibaList) {
            LXCustomFields lxCustomField = lxCustomFieldsMapper.selectByOptionValue(lxDeliveryAmibaId);
            externalList.add(lxCustomField.getOptionDesc());
        }

        List<String> localList = new ArrayList<>();
        //List<Order> deliveryOrders = lxOrderService.findListByCustomerOrderNo(customerOrder.getCustomerOrderNo())
        //        .stream()
        //        .filter(o -> !o.getStatus().equals(OrderStatus.STATUS_CANCEL))
        //        .collect(Collectors.toList());

        List<Order> deliveryOrders = lxOrderService.findListByCustomerOrderNo(customerOrder.getCustomerOrderNo());

        deliveryOrders.forEach(order -> localList.add(order.getDeliverManagerAmibaId().toString()));

        Map<String, String> differentSetMap = ListUtils.getDifferentSetFromTwoList(externalList, localList);
        if (differentSetMap.size() == 0) {
            log.info("受理交付部门未发生变化，无需调整");
            return;
        }

        log.info("受理交付部门发生变化，开始调整交付订单");
        for (Map.Entry<String, String> entry : differentSetMap.entrySet()) {
            if (entry.getValue().equals(ListUtils.INCREASE)) {
                log.info("受理交付部门发生变化，开始新增交付订单：受理部门：" + entry.getKey());
                //新增交付订单
                try {
                    String deliveryOrderNo = this.saveSingleDeliveryOrder(lxOrder, entry.getKey(), customerOrder.getCustomerOrderNo());

                    this.createInformationMessage(deliveryOrderNo, entry.getKey(), lxOrder.getUser().getId(), lxOrder.getId());
                } catch (Exception ex) {
                    log.error("同步订单错误: {}", ex.getMessage(), ex);
                    CompletableFuture.runAsync(() ->
                        sendNotifyMail(lxOrder, ex.getMessage()), taskExecutor)
                        .whenCompleteAsync((v, e) -> log.info("发送邮件完成"));
                }
                log.info("新增交付订单完成");
            }

            if (entry.getValue().equals(ListUtils.DECREASE)) {
                log.info("受理交付部门发生变化，开始取消交付订单：受理部门: " + entry.getKey());
                //取消交付订单
                Order order = lxOrderService.findByCustomerOrderNoAndDeliverManagerAmibaId(customerOrder.getCustomerOrderNo(), Integer.valueOf(entry.getKey()));
                if (order.getStatus().equals(OrderStatus.STATUS_CANCEL)) {
                    continue;
                }
                lxOrderService.cancelOrder(order.getOrderNo(), customerOrder.getBusinessManagerStaffName(), customerOrder.getBusinessManagerStaffCode());
                log.info("取消交付订单完成");
            }
        }

    }

    private void sendNotifyMail(Object lxOrder, String errMsg) {
        try {
            if (Objects.isNull(lxOrder)) {
                return;
            }

            MailMessage mailMessage = MailMessageBuilder.builder()
                .mailTypeEnum(MailTypeEnum.LX_ORDER_SYNC_ERROR)
                .subject("励销订单同步异常通知-" + mailConfigInfo.getActiveProfiles())
                .to(mailConfigInfo.getDefaultTo())
                .addData("title", "BOSS 励销订单同步异常通知")
                .addData("data", lxOrder)
                .addData("errorMsg", errMsg)
                .build();

            mailService.send(mailMessage);
            log.info("发送邮件完成");
        } catch (Exception ex) {
            log.error("发送邮件异常: {}", errMsg, ex);
        }
    }

}
